<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="单据号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入单据号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="单据状态" prop="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择单据状态" clearable >
                <el-option v-for="dict in stock_order_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="检验状态" prop="checkStatus">
              <el-select v-model="queryParams.checkStatus" placeholder="请选择检验状态" clearable >
                <el-option v-for="dict in stock_check_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="检验员" prop="checkBy">
              <el-input v-model="queryParams.checkBy" placeholder="请输入检验员" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['stock:inOrder:add']">新增</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['stock:inOrder:edit']">修改</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['stock:inOrder:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['stock:inOrder:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="inOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="orderId" v-if="false" />
        <el-table-column label="单据号" align="center" prop="orderNo" />
        <el-table-column label="单据类型" align="center" prop="orderType" >
          <template #default="scope">
            <dict-tag :options="stock_order_type" :value="scope.row.orderType"/>
          </template>
        </el-table-column>
        <el-table-column label="单据状态" align="center" prop="orderStatus" >
          <template #default="scope">
            <dict-tag :options="stock_order_status" :value="scope.row.orderStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="检验状态" align="center" prop="checkStatus" >
          <template #default="scope">
            <dict-tag :options="stock_check_status" :value="scope.row.checkStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="检验员" align="center" prop="checkBy" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="EditPen" @click="handleDetail(scope.row)" v-hasPermi="['stock:inOrder:edit']"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['stock:inOrder:edit']"></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['stock:inOrder:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改入库单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body :close-on-click-modal="false">
      <el-form ref="inOrderFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="选择物料标签">
              <el-button size="mini" type="success" icon="House" @click="openSelectMatLabelDialog">物料标签清单</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="matLabelList" style="width: 100%">
        <el-table-column label="物料编码" align="center" prop="matCode" width="100" />
        <el-table-column label="物料名称" align="center" prop="matName" width="120" />
        <el-table-column label="财务编码" align="center" prop="fdCode" width="100" />
        <el-table-column label="图号" align="center" prop="figNum" width="120" />
        <el-table-column label="数量" align="center" prop="quantity" width="80" />
        <el-table-column label="单价" align="center" prop="unitPrice" width="80" />
        <el-table-column label="单位" align="center" prop="unitCode" width="80"/>
        <el-table-column label="批次" align="center" prop="batch" width="160" />
        <el-table-column label="供应商" align="center" prop="supplierName" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="Close"
              @click="handleRemove(scope.$index,scope.row)"
            >去除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">创 建</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择物料标签对话框 -->
    <el-dialog :title="selectMatLabelDialog.title" v-model="selectMatLabelDialog.visible" width="1200px" append-to-body :close-on-click-modal="false" @open="onDialogOpen">
      <SelectMatLable ref="matLablePage" :labelIdArr="labelIdArr"
                      @confirmSelectArr="confirmSelectMatLabelArr" @confirmSelect="confirmSelectMatLabel">
      </SelectMatLable>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSelectMatLabel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 入库单详情对话框 -->
    <el-dialog class="detail-dialog" :title="inOrderDetailOpenDialog.title" v-model="inOrderDetailOpenDialog.visible" width="1300px" append-to-body :close-on-click-modal="false">
      <el-form ref="inOrderFormRef" :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库单号：">
              <span>{{form.orderNo}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单类型：">
              <template #default="scope">
                <dict-tag :options="stock_order_type" :value="form.orderType"/>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建人：">
              <span>{{form.createBy}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间：">
              <span>{{ parseTime(form.createTime) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table class="detail-table" :data="form.detailList|| []" style="width: 100%">
<!--        <el-table-column label="行号" align="center" prop="lineNo" type="index" />-->
        <el-table-column label="行号" align="center" prop="lineNo" width="100" />
        <el-table-column label="物料编码" align="center" prop="matCode" width="100" />
        <el-table-column label="物料名称" align="center" prop="matName" width="120" />
        <el-table-column label="财务编码" align="center" prop="fdCode" width="100" />
        <el-table-column label="图号" align="center" prop="figNum" width="120" />
        <el-table-column label="数量" align="center" prop="quantity" width="80" />
        <el-table-column label="单价" align="center" prop="unitPrice" width="80" />
        <el-table-column label="单位" align="center" prop="unitCode" width="80" />
        <el-table-column label="批次" align="center" prop="batch" width="180" />
        <el-table-column label="供应商" align="center" prop="supplierName" width="180" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="el-icon-printer" @click="handlePrintInOrder">打 印</el-button>
          <el-button @click="cancelOrderDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="InOrder" lang="ts">
import { listInOrder, getInOrder, delInOrder, addInOrder, updateInOrder, printInOrder } from '@/api/wmscloud/inOrder';
import { InOrderVO, InOrderQuery, InOrderForm } from '@/api/wmscloud/inOrder/types';
import { parseTime } from '@/utils/ruoyi';
import { MatLabelVO } from '@/api/wmscloud/matLabel/types';
import SelectMatLable from '@/views/wmscloud/components/SelectMatLabel/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { stock_order_status } = toRefs<any>(proxy?.useDict('stock_order_status'));
const { stock_check_status } = toRefs<any>(proxy?.useDict('stock_check_status'));
const { stock_order_type } = toRefs<any>(proxy?.useDict('stock_order_type'));

const inOrderList = ref<InOrderVO[]>([]);
const matLabelList = ref<MatLabelVO[]>([]);
const labelIdArr = ref<Array<string | number>>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const matLablePage = ref(null) // 对应组件的 ref

const queryFormRef = ref<ElFormInstance>();
const inOrderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const selectMatLabelDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const inOrderDetailOpenDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: InOrderForm = {
  orderId: undefined,
  orderNo: undefined,
  orderType: undefined,
  orderStatus: undefined,
  checkStatus: undefined,
  checkBy: undefined,
  detailList: []
}
const data = reactive<PageData<InOrderForm, InOrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    orderType: undefined,
    orderStatus: undefined,
    checkStatus: undefined,
    checkBy: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询入库单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInOrder(queryParams.value);
  inOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  labelIdArr.value = [];
  matLabelList.value = [];
  inOrderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: InOrderVO[]) => {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加入库单";
}
/** 选择物料标签按钮操作 */
const openSelectMatLabelDialog = () => {
  selectMatLabelDialog.visible = true;
  selectMatLabelDialog.title = "选择物料标签";
}

/** 查看入库单详细信息按钮操作 */
const handleDetail = async(row?: InOrderVO) => {
  reset();
  const _orderId = row?.orderId || ids.value[0]
  const res = await getInOrder(_orderId);
  console.log(res.data.detailList);
  Object.assign(form.value, res.data);
  inOrderDetailOpenDialog.visible = true;
  inOrderDetailOpenDialog.title = "入库单详细";
}
/** 关闭入库单详细信息按钮操作 */
const cancelOrderDetail = () => {
  reset();
  inOrderDetailOpenDialog.visible = false;
};

/** 打印按钮 */
const handlePrintInOrder = async () => {
  try {
    const res = await printInOrder(form.value.orderId); // 👈 调用你的入库单打印接口
    const binaryData = [];
    binaryData.push(res);
    const pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
    window.open(pdfUrl);
  } catch (error) {
    proxy?.$modal.msgError('入库单打印失败');
    console.error('打印入库单失败:', error);
  }
};
/** 打开选择物料标签窗口按钮操作 */
const onDialogOpen = () => {
  matLablePage.value?.getList?.()
}
/** 关闭选择物料标签窗口按钮操作 */
const cancelSelectMatLabel = () => {
  selectMatLabelDialog.visible = false;
};
/** 处理单选物料标签 */
const confirmSelectMatLabel = (item: MatLabelVO) => {
  matLabelList.value.unshift(item);
  labelIdArr.value.push(item.labelId);
  selectMatLabelDialog.visible = false;
};
/** 处理多选物料标签 */
const confirmSelectMatLabelArr = (arr: MatLabelVO[]) => {
  if (arr && arr.length > 0) {
    arr.forEach(item => {
      labelIdArr.value.push(item.labelId);
      matLabelList.value.unshift(item);
    });
  }
  selectMatLabelDialog.visible = false;
};

/** 去除物料标签 */
const handleRemove = (index: number, row: MatLabelVO) => {
  const labelIndex = labelIdArr.value.indexOf(row.labelId);
  if (labelIndex !== -1) {
    labelIdArr.value.splice(labelIndex, 1);
  }
  matLabelList.value.splice(index, 1);
};
/** 修改按钮操作 */
const handleUpdate = async (row?: InOrderVO) => {
  reset();
  const _orderId = row?.orderId || ids.value[0]
  const res = await getInOrder(_orderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改入库单";
}

/** 提交按钮 */
const submitForm = async () => {

  // 1. 校验物料标签是否为空
  if (!matLabelList.value || matLabelList.value.length === 0) {
    proxy?.$modal.msgError("请选择物料标签");
    return;
  }

  // 2. 确认提交
  try {
    await proxy?.$modal.confirm('是否确认创建入库单？');

    // 3. 填充表单字段
    form.value.detailList = matLabelList.value;
    form.value.orderType = 'purchase';

    // 4. 校验并提交
    inOrderFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        try {
          await addInOrder(form.value);
          proxy?.$modal.msgSuccess("新增成功");
          dialog.visible = false;
          await getList();
          matLabelList.value = [];
        } finally {
          buttonLoading.value = false;
        }
      }
    });
  } catch {

  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: InOrderVO) => {
  const _orderIds = row?.orderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除入库单编号为"' + _orderIds + '"的数据项？').finally(() => loading.value = false);
  await delInOrder(_orderIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wmsCloud/inOrder/export', {
    ...queryParams.value
  }, `inOrder_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
